package com.xhsj.user.sms.base;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhsj.user.utils.IdGen;
import com.xhsj.user.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author suxl
 * @date 2018年10月8日 下午4:37:35
 */
@Slf4j
public abstract class BaseService<M extends BaseMapper<T>, T extends BaseEntity<T>> extends ServiceImpl<M, T> {
    @Autowired
    private M dao;

//    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean save(T entity) {
            if (StringUtils.isBlank(entity.getId())) {
                String uuid = IdGen.uuid();
                entity.setId(uuid);
                entity.setCreateDate(entity.getCreateDate()==null?new Date():entity.getCreateDate());
                entity.setUpdateDate(entity.getUpdateDate()==null?new Date():entity.getUpdateDate());
//                entity.setCreateDate(new Date());
//                entity.setUpdateDate(new Date());
//                entity.setCreateBy(UserUtils.getLoginAppUser()==null?"1":UserUtils.getLoginAppUser().getId());
//                entity.setCreateName(UserUtils.getLoginAppUser()==null?"":UserUtils.getLoginAppUser().getUsername());
//                entity.setUpdateBy(UserUtils.getLoginAppUser()==null?"1":UserUtils.getLoginAppUser().getId());
//                entity.setUpdateName(UserUtils.getLoginAppUser()==null?"":UserUtils.getLoginAppUser().getUsername());
                entity.setDelFlag(0);
                int insert = dao.insert(entity);
                if (insert == 0) {
                    log.error("新增影响行数为0");
                    return false;
                }
            } else {
//                entity.setUpdateBy(UserUtils.getLoginAppUser()==null?"1":UserUtils.getLoginAppUser().getId());
//                entity.setUpdateName(UserUtils.getLoginAppUser()==null?"":UserUtils.getLoginAppUser().getUsername());
                entity.setUpdateDate(new Date());
                int i = dao.updateById(entity);
                if (i == 0) {
                    log.error("修改影响行数为0");
                    return false;
                }
            }
            return true;
    }


    public List<T> selectAll() {
        QueryWrapper<T> wrapper = new QueryWrapper<T>();
        wrapper.setEntity(null);
        return dao.selectList(wrapper);
    }

    /**
     * 分页查询   支持模糊查询
     * @param page
     * @param queryWrapper
     * @return
     */
    public IPage<T> selectPage(IPage<T> page, QueryWrapper<T> queryWrapper) {

        try {

            T entity = queryWrapper.getEntity();
            if (entity!=null){
                //匹配模糊查询
//                Class<?> aClass = entity.getClass();
                for (Class<?> superClass = entity.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
                    Field[] declaredFields = superClass.getDeclaredFields();
                    for (Field declaredField : declaredFields) {
                        declaredField.setAccessible(true);
                        TableField annotation = declaredField.getAnnotation(TableField.class);
                        if (annotation!=null) {
                            //数据库列名
                            String value = annotation.value();

                            //属性值
                            Object o = declaredField.get(entity);
                            String val;
                            if (Objects.nonNull(o)){
                                if (o instanceof String) {
                                    val = ((String)o).trim();
                                    if (StringUtils.isNotBlank(val)){
                                        if (StringUtils.isNotBlank(val) && !val.equals("%") && !val.equals("%%")){
//                                            if (val.startsWith("%") && !val.endsWith("%")){
//                                                queryWrapper.likeLeft(value,val.replace("%",""));
//                                                declaredField.set(entity,null);
//                                            }else if (!val.startsWith("%") && val.endsWith("%")){
//                                                queryWrapper.likeRight(value,val.replace("%",""));
//                                                declaredField.set(entity,null);
//                                            }else if(val.startsWith("%") && val.endsWith("%")){
                                                queryWrapper.like(value,val.replace("%",""));
                                                declaredField.set(entity,null);
//                                            }
                                        }
                                    }else{
                                        declaredField.set(entity,null);
                                    }

                                }

                            }else{
                                declaredField.set(entity,null);
                            }
                        }

                    }

                    //排序
                    List<Map<String, String>> orderBy = entity.getOrderBy();
                    if (orderBy.size()>0) {
                        for (Map<String, String> map : orderBy) {
                            String name = map.get("name");
                            String sort = map.get("sort");
                            String cloum="";
                            for (Field declaredField : declaredFields) {
                                declaredField.setAccessible(true);
                                if (name.equals(declaredField.getName())) {//排序属性和实体类属性相同
                                    TableField annotation = declaredField.getAnnotation(TableField.class);
                                    //数据库列名
                                    cloum = annotation.value();
                                    break;
                                }
                            }
                            if (StringUtils.isNotBlank(cloum)) {
                                if ("asc".equals(sort)) {
                                    queryWrapper.orderByAsc(cloum);
                                }if ("desc".equals(sort)) {
                                    queryWrapper.orderByDesc(cloum);
                                }
                            }
                        }
                    }
                }


            }




        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }


        return this.dao.selectPage(page, queryWrapper);
    }


}
